const jwt = require('jsonwebtoken')
const errorTypes = require('../constants/error-types')
const UserService = require('../service/login.service')
const { PUBLIC_KEY } = require('../app/config')

const ignoreVerifyUrl = [
  '/user/login',
  '/user/userinfo',
  '/user/register',
  '/users/avatar',
  '/system/images',
  '/article/list/web',
  '/article/detail/web',
]

// 用户登录
const verifyLogin = async (ctx, next) => {
  // 1. 获取用户名和密码
  const { account, password } = ctx.request.body
  // 2. 判断用户名和密码是否为空
  if (!account || !password) {
    const error = new Error(errorTypes.ACCOUNT_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }
  // 3. 判断用户是否存在
  const result = await UserService.getUserByAccount(account)
  const user = result[0]
  if (!user) {
    const error = new Error(errorTypes.USER_DOES_NOT_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  // 4.判断密码是否和数据库中的密码是一致(加密)
  if (password !== user.password) {
    const error = new Error(errorTypes.PASSWORD_IS_INCORRENT)
    return ctx.app.emit('error', error, ctx)
  }
  ctx.user = user
  await next()
}

const verifyToken = async (ctx, next) => {
  const url = ctx.request.url
  for (const ignoreUrl of ignoreVerifyUrl) {
    if (url.includes(ignoreUrl)) {
      return await next()
    }
  }
  // 1. 获取token
  const authorization = ctx.headers.authorization
  if (!authorization) {
    const error = new Error(errorTypes.UNAUTHORIZATION)
    ctx.app.emit('error', error, ctx)
    return
  }
  const token = authorization.replace('Bearer', '')

  // 2. 验证token
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256'],
    })
    ctx.user = result
    await next()
  } catch (err) {
    console.log('auth.mid.js ===> catch: ', err)
    const error = new Error(errorTypes.UNAUTHORIZATION)
    ctx.app.emit('error', error, ctx)
  }
}

module.exports = {
  verifyLogin,
  verifyToken,
}
